import { message, Modal, Upload } from 'antd';
import React, { useState } from 'react';
import { baseURL } from 'utils/request';
import { getToken } from 'utils/storage';
import { UploadOutlined } from '@ant-design/icons';

//上传图片到自己的服务器
export default function TextPage() {
  const [imgSrc, setImgSrc] = useState('');
  //2.2声明状态控制Upload 的fileList 等价于表单的value
  const [fileList, setFileList] = useState([]);
  //1,提取了配置props
  const props = {
    //打开文件窗口时  可以默认显示文件类型
    accept: '.png,.jpg',
    //1.1 name代表后台支持上传文件的类型  值由后台决定
    name: 'image',
    //1.2 代表上传文件的请求url地址
    action: `${baseURL}/v1_0/upload`,
    //1.3 加上token 预防别人恶意上传 弄蹦服务器
    headers: {
      authorization: `Bearer ${getToken()}`,
    },
    // 2.1上传文件改变时的状态
    onChange(info) {
      console.log(24, info);
      // 2.3 onChange事件改变fileList 并且 fileList 绑定在Upload 的props身上
      setFileList(info.fileList);
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    },
    //点击小眼睛  放大
    onPreview(file) {
      console.log('11', file);
      setImgSrc(file.thumbUrl);
    },

    //1上传文件之前的钩子
    beforeUpload(file) {
      //2,判断file.type的值 阻止非图片的文件上传
      //白名单
      const imgs = ['image/jpg', 'image/png', 'image/jpeg'];

      //3,阻止图片上传
      if (!imgs.includes(file.type)) {
        message.warning('不允许上传的文件类型', 1);
        // Upload.LIST_IGNORE  阻止发起请求,也不在前端界面显示图片
        return Upload.LIST_IGNORE;
      }
    },
  };
  return (
    <div>
      <Upload {...props} listType="picture-card" fileList={fileList}>
        {/* 2.4  判断fileList 的数量  是否显示按钮*/}
        {fileList.length === 3 ? null : <UploadOutlined />}
      </Upload>

      {/* 模态框 显示图片 */}
      <Modal
        title="预览图片"
        visible={!!imgSrc}
        onCancel={() => setImgSrc('')}
        footer={null}
      >
        <img src={imgSrc} alt="" />
      </Modal>
    </div>
  );
}
